/**
 * 
 */
package de.mbenning.fsim.web.controller.laender;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import de.mbenning.fsim.domain.Land;
import de.mbenning.fsim.persistence.dao.interfaces.IMainDAO;
import de.mbenning.fsim.web.controller.AbstractFsimBaseController;
import de.mbenning.fsim.web.servlet.ServletRequestHelper;

/**
 * @author Martin.Benning
 *
 */
public class LandEditFormController extends AbstractFsimBaseController {
	
	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		Integer landId = ServletRequestUtils.getIntParameter(request, "land.id", -1);
		Land land = new Land(); 
		if(landId.intValue() > 0) {
			land = mainDAO.getLandById(landId);
		}
		return land;
	}
	
	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		Map<String, Object> model = new HashMap<String, Object>();
		Land land = (Land) command;
		model.put("land", land);
		model.put("kontinente", mainDAO.findAllKontinent());
		return model;
	}
	
	@Override
	protected void onBindAndValidate(HttpServletRequest request,
		Object command, BindException errors) throws Exception {
		Land land = (Land) command;
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		Land land = (Land) command;
		String filename = ServletRequestHelper.uploadFile(request, "flaggeImage");
		land.setFlagge(filename);
		mainDAO.store(land);
		
		return new ModelAndView(new RedirectView("list.htm"));
	}
	
	public IMainDAO getMainDAO() {
		return mainDAO;
	}

	public void setMainDAO(IMainDAO mainDAO) {
		this.mainDAO = mainDAO;
	}

}
